from django.core.paginator import Paginator, EmptyPage
from django.shortcuts import render
from django.views import View
from django import http

from haystack.views import SearchView
from apps.contents.utils import get_categories
from apps.goods.models import GoodsCategory, SKU
from apps.goods.utils import get_breadcrumb, get_goods_specs
from meiduo_mall.settings.dev import logger


# Create your views here.
class DetailVisitView(View):
    """详情页分类商品访问量"""
    def post(self, request, category_id):
        try:
            # 1.获取当前商品
            category = GoodsCategory.objects.get(id=category_id)
        except Exception as e:
            return http.JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})

        # 2.查询日期数据
        from datetime import date
        # 获取当天日期
        today_date = date.today()

        from apps.goods.models import GoodsVisitCount
        try:
            # 3.如果有当天商品分类的数据  就累加数量
            # count_data = GoodsVisitCount.objects.get(data=today_date, category=category)
            count_data = category.goodsvisitcount_set.get(date=today_date)
        except:
            # 4. 没有, 就新建之后在增加
            count_data = GoodsVisitCount()

        try:
            count_data.count += 1
            count_data.category = category
            count_data.save()
        except Exception as e:
            return http.HttpResponseServerError('新增失败')

        return http.JsonResponse({'code': 0, 'errmsg': 'OK'})


class DetailView(View):
    """商品详情页"""

    def get(self, request, sku_id):
        """提供商品详情页"""
        # 获取当前sku的信息
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return render(request, '404.html')

        # 查询商品频道分类
        categories = get_categories()
        # 查询面包屑导航
        breadcrumb = get_breadcrumb(sku.category)
        # 构建当前商品的规格键
        goods_specs = get_goods_specs(sku)

        # 渲染页面
        context = {
            'categories': categories,
            'breadcrumb': breadcrumb,
            'sku': sku,
            'specs': goods_specs,
        }
        return render(request, 'detail.html', context)


class MySearchView(SearchView):
    '''重写SearchView类'''

    def create_response(self):
        page = self.request.GET.get('page')
        # 获取搜索结果
        context = self.get_context()
        data_list = []
        for sku in context['page'].object_list:
            data_list.append({
                'id': sku.object.id,
                'name': sku.object.name,
                'price': sku.object.price,
                'default_image_url': sku.object.default_image.url,
                'searchkey': context.get('query'),
                'page_size': context['page'].paginator.num_pages,
                'count': context['page'].paginator.count
            })
        # 拼接参数, 返回
        return http.JsonResponse(data_list, safe=False)


class HotGoodsView(View):
    """商品热销排行"""

    def get(self, request, category_id):
        # 校验category_id
        try:
            GoodsCategory.objects.get(pk=category_id)
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '分类不存在'})

        # 根据销量倒序
        try:
            skus = SKU.objects.filter(category_id=category_id, is_launched=True).order_by('-sales')[:2]
        except Exception as e:
            return http.JsonResponse({'code': 400, 'errmsg': '获取商品出错'})

        # 转换格式:
        hot_list = []
        for sku in skus:
            hot_list.append({
                'id': sku.id,
                'default_image_url': sku.default_image.url,
                'name': sku.name,
                'price': sku.price
            })

        return http.JsonResponse({'code': 0, 'errmsg': 'OK', 'hot_skus': hot_list})


class ListView(View):
    """商品列表页"""

    def get(self, request, category_id):
        """提供商品列表页"""
        # 获取参数:
        page_num = request.GET.get('page')
        page_size = request.GET.get('page_size')
        sort = request.GET.get('ordering')

        # 判断category_id是否正确
        try:
            # 获取三级菜单分类信息:
            category = GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoesNotExist:
            return http.JsonResponse({'code': 400, 'errmsg': '获取mysql数据出错'})

        # 查询面包屑导航(封装在goods.utils中)
        breadcrumb = get_breadcrumb(category)

        # 排序方式:
        try:
            skus = SKU.objects.filter(category=category,
                                      is_launched=True).order_by(sort)
        except SKU.DoesNotExist:
            return http.JsonResponse({'code': 400,
                                      'errmsg': '获取mysql数据出错'})

        paginator = Paginator(skus, 5)
        # 获取每页商品数据
        try:
            page_skus = paginator.page(page_num)
        except EmptyPage:
            # 如果page_num不正确，默认给用户400
            return http.JsonResponse({'code': 400,
                                      'errmsg': 'page数据出错'})
        # 获取列表页总页数
        total_page = paginator.num_pages

        # 定义列表:
        data_list = []
        # 整理格式:
        for sku in page_skus:
            data_list.append({
                'id': sku.id,
                'default_image_url': sku.default_image.url,
                'name': sku.name,
                'price': sku.price
            })

        # 把数据变为 json 发送给前端
        return http.JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'breadcrumb': breadcrumb,  # 面包屑导航
            'list': data_list,
            'count': total_page
        })
